"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Plus, Search, Edit, Trash2, MoreHorizontal, Shield } from "lucide-react"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Checkbox } from "@/components/ui/checkbox"

// 模拟角色数据
const mockRoles = [
  {
    id: 1,
    name: "超级管理员",
    code: "super_admin",
    description: "拥有系统所有权限的最高管理员",
    userCount: 1,
    permissions: ["user:read", "user:write", "role:read", "role:write", "permission:read", "permission:write"],
    createdAt: "2024-01-15",
    status: "active",
  },
  {
    id: 2,
    name: "管理员",
    code: "admin",
    description: "系统管理员，拥有大部分管理权限",
    userCount: 3,
    permissions: ["user:read", "user:write", "role:read", "permission:read"],
    createdAt: "2024-01-16",
    status: "active",
  },
  {
    id: 3,
    name: "普通用户",
    code: "user",
    description: "系统普通用户，拥有基础功能权限",
    userCount: 156,
    permissions: ["user:read"],
    createdAt: "2024-01-17",
    status: "active",
  },
  {
    id: 4,
    name: "访客",
    code: "guest",
    description: "访客用户，只能查看基础信息",
    userCount: 23,
    permissions: [],
    createdAt: "2024-01-18",
    status: "inactive",
  },
]

// 模拟权限数据
const mockPermissions = [
  { id: "user:read", name: "查看用户", module: "用户管理" },
  { id: "user:write", name: "编辑用户", module: "用户管理" },
  { id: "role:read", name: "查看角色", module: "角色管理" },
  { id: "role:write", name: "编辑角色", module: "角色管理" },
  { id: "permission:read", name: "查看权限", module: "权限管理" },
  { id: "permission:write", name: "编辑权限", module: "权限管理" },
  { id: "menu:read", name: "查看菜单", module: "菜单管理" },
  { id: "menu:write", name: "编辑菜单", module: "菜单管理" },
]

export default function RolesPage() {
  const [roles, setRoles] = useState(mockRoles)
  const [searchTerm, setSearchTerm] = useState("")
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [selectedRole, setSelectedRole] = useState<any>(null)
  const [newRole, setNewRole] = useState({
    name: "",
    code: "",
    description: "",
    permissions: [] as string[],
  })

  const filteredRoles = roles.filter(
    (role) =>
      role.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      role.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
      role.description.toLowerCase().includes(searchTerm.toLowerCase()),
  )

  const handleAddRole = () => {
    const role = {
      id: roles.length + 1,
      ...newRole,
      userCount: 0,
      createdAt: new Date().toISOString().split("T")[0],
      status: "active",
    }
    setRoles([...roles, role])
    setNewRole({ name: "", code: "", description: "", permissions: [] })
    setIsAddDialogOpen(false)
  }

  const handleEditRole = () => {
    setRoles(roles.map((role) => (role.id === selectedRole.id ? { ...role, ...selectedRole } : role)))
    setIsEditDialogOpen(false)
    setSelectedRole(null)
  }

  const handleDeleteRole = (id: number) => {
    setRoles(roles.filter((role) => role.id !== id))
  }

  const getStatusBadge = (status: string) => {
    return status === "active" ? (
      <Badge variant="default" className="bg-foreground text-background">
        启用
      </Badge>
    ) : (
      <Badge variant="secondary" className="bg-gray-100 text-gray-800">
        禁用
      </Badge>
    )
  }

  const handlePermissionChange = (permissionId: string, checked: boolean, isEdit = false) => {
    if (isEdit && selectedRole) {
      const updatedPermissions = checked
        ? [...selectedRole.permissions, permissionId]
        : selectedRole.permissions.filter((p: string) => p !== permissionId)
      setSelectedRole({ ...selectedRole, permissions: updatedPermissions })
    } else {
      const updatedPermissions = checked
        ? [...newRole.permissions, permissionId]
        : newRole.permissions.filter((p) => p !== permissionId)
      setNewRole({ ...newRole, permissions: updatedPermissions })
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold tracking-tight">角色管理</h2>
          <p className="text-muted-foreground">管理系统角色和权限分配</p>
        </div>
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              添加角色
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader>
              <DialogTitle>添加新角色</DialogTitle>
              <DialogDescription>创建一个新的系统角色并分配权限</DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">
                  角色名称
                </Label>
                <Input
                  id="name"
                  value={newRole.name}
                  onChange={(e) => setNewRole({ ...newRole, name: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="code" className="text-right">
                  角色代码
                </Label>
                <Input
                  id="code"
                  value={newRole.code}
                  onChange={(e) => setNewRole({ ...newRole, code: e.target.value })}
                  className="col-span-3"
                  placeholder="例如: admin, user"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right">
                  描述
                </Label>
                <Textarea
                  id="description"
                  value={newRole.description}
                  onChange={(e) => setNewRole({ ...newRole, description: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-start gap-4">
                <Label className="text-right mt-2">权限分配</Label>
                <div className="col-span-3 space-y-2 max-h-48 overflow-y-auto">
                  {mockPermissions.map((permission) => (
                    <div key={permission.id} className="flex items-center space-x-2">
                      <Checkbox
                        id={permission.id}
                        checked={newRole.permissions.includes(permission.id)}
                        onCheckedChange={(checked) => handlePermissionChange(permission.id, checked as boolean)}
                      />
                      <Label htmlFor={permission.id} className="text-sm">
                        <span className="font-medium">{permission.name}</span>
                        <span className="text-muted-foreground ml-2">({permission.module})</span>
                      </Label>
                    </div>
                  ))}
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button type="submit" onClick={handleAddRole}>
                创建角色
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>角色列表</CardTitle>
          <CardDescription>系统中所有角色的详细信息</CardDescription>
          <div className="flex items-center space-x-2">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="搜索角色..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-8"
              />
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>角色名称</TableHead>
                <TableHead>角色代码</TableHead>
                <TableHead>描述</TableHead>
                <TableHead>用户数量</TableHead>
                <TableHead>权限数量</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead className="text-right">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredRoles.map((role) => (
                <TableRow key={role.id}>
                  <TableCell className="font-medium">
                    <div className="flex items-center">
                      <Shield className="mr-2 h-4 w-4 text-primary" />
                      {role.name}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">{role.code}</Badge>
                  </TableCell>
                  <TableCell className="max-w-xs truncate">{role.description}</TableCell>
                  <TableCell>{role.userCount}</TableCell>
                  <TableCell>{role.permissions.length}</TableCell>
                  <TableCell>{getStatusBadge(role.status)}</TableCell>
                  <TableCell>{role.createdAt}</TableCell>
                  <TableCell className="text-right">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" className="h-8 w-8 p-0">
                          <span className="sr-only">打开菜单</span>
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem
                          onClick={() => {
                            setSelectedRole(role)
                            setIsEditDialogOpen(true)
                          }}
                        >
                          <Edit className="mr-2 h-4 w-4" />
                          编辑
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => handleDeleteRole(role.id)} className="text-destructive">
                          <Trash2 className="mr-2 h-4 w-4" />
                          删除
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* 编辑角色对话框 */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>编辑角色</DialogTitle>
            <DialogDescription>修改角色信息和权限分配</DialogDescription>
          </DialogHeader>
          {selectedRole && (
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-name" className="text-right">
                  角色名称
                </Label>
                <Input
                  id="edit-name"
                  value={selectedRole.name}
                  onChange={(e) => setSelectedRole({ ...selectedRole, name: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-code" className="text-right">
                  角色代码
                </Label>
                <Input
                  id="edit-code"
                  value={selectedRole.code}
                  onChange={(e) => setSelectedRole({ ...selectedRole, code: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-description" className="text-right">
                  描述
                </Label>
                <Textarea
                  id="edit-description"
                  value={selectedRole.description}
                  onChange={(e) => setSelectedRole({ ...selectedRole, description: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-start gap-4">
                <Label className="text-right mt-2">权限分配</Label>
                <div className="col-span-3 space-y-2 max-h-48 overflow-y-auto">
                  {mockPermissions.map((permission) => (
                    <div key={permission.id} className="flex items-center space-x-2">
                      <Checkbox
                        id={`edit-${permission.id}`}
                        checked={selectedRole.permissions.includes(permission.id)}
                        onCheckedChange={(checked) => handlePermissionChange(permission.id, checked as boolean, true)}
                      />
                      <Label htmlFor={`edit-${permission.id}`} className="text-sm">
                        <span className="font-medium">{permission.name}</span>
                        <span className="text-muted-foreground ml-2">({permission.module})</span>
                      </Label>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button type="submit" onClick={handleEditRole}>
              保存更改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
